package com.beiding.my.mql.utils;


import java.util.*;

public class KeywordGroup {

    private String[] keywords;
    private String text;

    //关键词区块
    private Map<String, KeywordBlock> blockMap = new HashMap<>();

    public KeywordGroup(String text, String... keywords) {
        this.text = text;
        this.keywords = keywords;
    }

    //从前到后进行获取
    public void find() {

        String k = " " + text;

        //屏蔽掉字符串
        StringHide hide = MqlUtils.hideString(k);
        String noString = hide.getResult();

        List<Position> list = new ArrayList<>();

        for (String keyword : keywords) {
            int index = 0;
            while (true) {

                index = noString.indexOf(" " + keyword + " ", index);
                if (index == -1) {
                    break;
                } else {
                    Position o = new Position(index);
                    list.add(o);
                    o.setA1(keyword);
                    index = index + keyword.length() - 1;//比实际坐标前移一位 因为 k 加了 " "
                }
            }
        }

        //进行一次排序操作
        list.sort(Comparator.comparingInt(Position::getIndex));

        for (int i = 0; i < list.size(); i++) {
            Position position = list.get(i);

            //计算后一个节点
            int end = text.length() - 1;
            if (i + 1 < list.size()) {
                end = list.get(i + 1).getIndex() - 1;
            }

            KeywordBlock keywordBlock = new KeywordBlock();
            keywordBlock.setKeyword(position.getA1());

            keywordBlock.setStart(position.getIndex());
            keywordBlock.setEnd(end);
            keywordBlock.cutText(text);

            //构建值的部分
            keywordBlock.setKeywordValue(text.substring(position.getIndex() + position.getA1().length() + 1, end).trim());
            if (blockMap.put(keywordBlock.getKeyword(), keywordBlock) != null) {
                throw new RuntimeException("关键字结果不唯一: " + text + "   key:" + keywordBlock.getKeyword());
            }
        }
    }

    public Map<String, KeywordBlock> getBlockMap() {
        return blockMap;
    }
}

